package com.suda.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.suda.entity.User;
import com.suda.service.UserService;
import com.suda.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String,Object> login(User user){
        Map<String,Object> map = new HashMap<>();
        try{
            User userDB = this.userService.login(user);
            //生成JWT的令牌
            Map<String,String> payload = new HashMap<>();
            payload.put("id",userDB.getId());
            payload.put("name",userDB.getName());
            String token = JWTUtils.getToken(payload);
            //在认证成功时,需要将Token返回
            map.put("token",token);
            map.put("state",true);
            map.put("msg","认证成功");
        }catch (RuntimeException e){
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }


    @GetMapping("/test")
    public Map<String,Object> test(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //正常处理业务逻辑,当需要用到token中的内容时可以取出
        String token = request.getHeader("token");
        DecodedJWT info = JWTUtils.getToken(token);
        String id = info.getClaim("id").asString();
        String name = info.getClaim("name").asString();
        map.put("state",true);
        map.put("msg","请求成功");
        return map;
    }
}
